<template>
    <div>
        <h2>文件上传</h2>
        <input type="file" @change="onFileChange" />
        <button @click="uploadFile">上传</button>
        <p v-if="uploadError">{{ uploadError }}</p>
        <p v-if="uploadSuccess">{{ uploadSuccess }}</p>
    </div>
</template>

<script setup>
    import {BASE_URL} from '@/utils/common.js'
    const selectedFile = ref(null);  
    const uploadError = ref('');  
    const uploadSuccess = ref('');  

    const onFileChange = (e) => {  
      selectedFile.value = e.target.files[0];  
    };  

   const uploadFile = async () => {  
      if (!selectedFile.value) {  
        return alert('请先选择一个文件！');  
      }  
  
      const formData = new FormData();  
      formData.append('file', selectedFile.value);  
  
      try {  
        const response = await axios.post(BASE_URL+'/upload', formData, {  
          headers: {  
            'Content-Type': 'multipart/form-data',  
          },  
        });  
  
        uploadSuccess.value = '文件上传成功！';  
        uploadError.value = '';  
        // 根据需要处理响应数据  
        console.log(response.data);  
      } catch (error) {  
        uploadError.value = '文件上传失败：' + error.message;  
        uploadSuccess.value = '';  
        console.error(error);  
      }  
    };  

</script>
